﻿using Dapper;
using MediatR;
using MySql.Data.MySqlClient;
using System.Text;
using Warehouse.Api.Read.AGCation.Command;
using Warehouse.Api.Read.Dtos;
using Warehouse.ErrorCode;
using Warehouse.Infrastructrue.Implenment;

namespace Warehouse.Api.Read.AGCation.Hanlder
{
    public class AllCommandHanlder : IRequestHandler<AllCommand, ApiPaging<TransferDto>>
    {
        DbContext db;
        ILogger<AllCommandHanlder> logger;

        public AllCommandHanlder(DbContext db, ILogger<AllCommandHanlder> logger)
        {
            this.db = db;
            this.logger = logger;
        }
        /// <summary>
        /// 调拨的查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>

        public async Task<ApiPaging<TransferDto>> Handle(AllCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<TransferDto> result = new ApiPaging<TransferDto>();
            try
            {
                if (request.PageSize <= 0)
                {
                    result.Msg = "显示数量不能小于等于0";
                    result.Code = ApiEume.Error;
                    return result;
                }

                StringBuilder sqlbuilder = new StringBuilder();
                StringBuilder countsql = new StringBuilder();

                sqlbuilder.Append(@" SELECT 
                   a.AssociatedOrderNumber,
                   a.SupplierName,
                   a.IncomingQuantity,
                   a.Totalprice,   
                   a.PreparedName,
                   a.PreparedTime,
                   b.ProductName,
                   a.Price,                     
          c.LocationName,
          d.AllocateWarehouseIn,       
          d.OrderNumber                
          FROM 
              stocking a  
             JOIN ProductModel b ON a.ProductId = b.ProductId 
             JOIN LocationModel c ON a.StorageId = c.LocationId
             LEFT JOIN AllocateModel d ON a.AllocateId = d.AllocateId 
             WHERE  a.IsDeleted = 0  ");

                countsql.Append(@" SELECT (count(*)) FROM 
            stocking a  
          JOIN ProductModel b ON a.ProductId = b.ProductId 
          JOIN LocationModel c ON a.StorageId = c.LocationId 
          LEFT JOIN AllocateModel d ON a.AllocateId = d.AllocateId  
          WHERE a.IsDeleted = 0  ");
                var parameters = new DynamicParameters();
 
                // 分页部分代码（仅修改此段）
                sqlbuilder.Append("LIMIT @PageSize offset @Offset");  // 修正 LIMIT 语法（参数化 PageSize）
               // 修正拼写：parameters
                parameters.Add("PageSize", request.PageSize);
                parameters.Add("offset", (request.PageIndex - 1) * request.PageSize);
                using var conn = new MySqlConnection("server=120.27.210.76;uid=wms_user;pwd=MyPassword123!;database=warehousemanagement;CharSet=utf8mb4");
                await conn.OpenAsync(cancellationToken);
                var data = await conn.QueryAsync<TransferDto>(sqlbuilder.ToString(), parameters);
                var total = await conn.ExecuteScalarAsync<int>(countsql.ToString(), parameters);
                // 结果赋值部分保持你的格式
                result.PageData = data.ToList();
                result.TotaCount = total;
                result.PageCount = (int)Math.Ceiling((double)total / request.PageSize);
                result.Msg = "显示成功";

            }
            catch (Exception ex)
            {
                result.Msg = "显示失败";
                result.Code = ApiEume.Error;
                logger.LogError(ex, "显示调拨记录失败");
            }
            return result;
        }
    }
}




